package hc.bre.rest.cmn

import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice

/**
 * {@link IgnorReponseAdvice} 处理解析 {@link ResponseBodyAdvice} 统一返回包装器
 * 实现参考下文link https://segmentfault.com/a/1190000020517960?utm_source=tag-newest
 */
@groovy.transform.CompileStatic
@RestControllerAdvice
class ResponseResultAdvice implements  ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		// 检查注解是否存在
		if (returnType.getMethod().isAnnotationPresent(IgnoreReponseAdvice.class)) {
			return false;
		}
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {

		if(body == null)
		{
			return new ReturnResult(null);
		}

		if (body instanceof ReturnResult) {
			return body;
		}

		//deal String type specially
		if (body instanceof String) {
			return hc.Util.jsonWrite(new ReturnResult(body));
		}


		return new ReturnResult(body);
	}
}
